<template>
  <div>
    <a-card>
      <a-space size="medium">
        <!-- 按钮，点击后触发抽屉打开 -->
        <div :style="{ marginTop: '0px' }">
          <a-button type="primary" @click="handleClick">分配班级</a-button>
        </div>

        <div>
          <span style="font-weight: 600; margin-right: 10px">姓名:</span>
          <a-input
            :style="{ width: '220px', height: '32px' }"
            placeholder="输入学生姓名或关键字"
            :max-length="10"
            allow-clear
            show-word-limit
            @input="InputTrigger($event)"
            @clear="clearInput()"
          />
        </div>

        <div>
          <span style="font-weight: 600; margin-right: 10px">年级:</span>
          <a-checkbox-group
            :default-value="checkedList"
            @change="onChange($event)"
          >
            <a-checkbox value="小班">小班</a-checkbox>
            <a-checkbox value="中班">中班</a-checkbox>
            <a-checkbox value="大班">大班</a-checkbox>
          </a-checkbox-group>
        </div>

        <!-- 抽屉组件配置 -->
        <!-- :width="340" 抽屉宽度
            :height="340" 抽屉高度
            :visible="visible" 控制抽屉的显示与隐藏
            :placement="position" 抽屉弹出的位置，由单选按钮组决定
            @ok="handleOk" 点击确定按钮时触发的事件
            @cancel="handleCancel" 点击取消按钮或遮罩层时触发的事件
            unmountOnClose 关闭抽屉时卸载DOM元素，优化性能 -->
        <a-drawer
          :width="340"
          :height="340"
          :visible="visible02"
          :placement="position"
          @ok="handleOk"
          @cancel="handleCancel"
          unmountOnClose
        >
          <!-- 自定义抽屉标题 -->
          <template #title>班级分配</template>

          <!-- 抽屉内容区域 -->
          <div>
            <a-table
              :data="recordsWithEmptyClassId"
              :bordered="{ cell: true }"
              :pagination="false"
              row-key="id"
              :rowSelection="{
                type: 'checkbox',
                showCheckedAll: true,
                onlyCurrent: false,
              }"
              v-model:selectedKeys="selectEroll"
            >
              <template #columns>
                <a-table-column
                  title="学生姓名"
                  data-index="name"
                ></a-table-column>
                <a-table-column
                  title="所属年级"
                  data-index="classGradeLevel"
                ></a-table-column>
                <a-table-column title="分配班级">
                  <template #cell="{ record }">
                    <!-- 将a-switch替换为a-select以创建下拉选择框 -->
                    <a-select
                      @change="onStatusChange($event, record)"
                      @popup-visible-change="onVisibleChange(record)"
                      size="small"
                      placeholder="待分配"
                    >
                      <!-- 遍历状态选项并为每个选项创建一个a-select-option -->
                      <a-option v-for="option in classesListInfo">
                        {{ option.className }}
                      </a-option>
                    </a-select>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </div>
        </a-drawer>
      </a-space>
    </a-card>

    <a-card>
      <!-- 这里是表的复选框 -->
      <a-table
        :data="enrollInfoArr"
        :bordered="{ cell: true }"
        :pagination="false"
        row-key="id"
        :rowSelection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }"
        v-model:selectedKeys="selectEroll"
      >
        <template #columns>
          <a-table-column title="学生姓名" data-index="name"></a-table-column>

          <a-table-column
            title="紧急联系人电话"
            data-index="emergencyContactPhone"
          ></a-table-column>
          <a-table-column
            title="入圆日期"
            data-index="admissionDate"
          ></a-table-column>
          <a-table-column
            title="所属年级"
            data-index="classGradeLevel"
          ></a-table-column>
          <a-table-column
            title="是否在读"
            data-index="graduated"
          ></a-table-column>
        </template>
      </a-table>

      <a-pagination
        @change="getStuInfo"
        @page-size-change="pageSizeChange"
        style="margin-top: 15px"
        :total="total"
        show-total
        show-page-size
        :page-size="pageSize"
        :current="pageNo"
      />
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  reqstupageinfo,
  reqAssignUpdateClasses,
  getStuByNameAndClassLevels,
} from '@/api/stuInfo/index'
// import { reqClassesPageInfo } from '@/api/classroom/index'
import { StuInfo } from '@/api/stuInfo/type'
import { Classrs } from '@/api/classroom/type'
import { reqClassesInfoListDistribute } from '@/api/classroom/index'
// 从Vue的核心库中导入onMounted钩子函数
// reactive用于创建响应式对象，使对象的属性变化能够驱动视图更新
// ref用于创建带有.value属性的响应式引用，可用于任何类型的值，包括对象、数组等
import { onMounted, reactive, ref, nextTick } from 'vue'
// 从Arco Design Web Vue组件库中导入Message组件
// Message组件通常用于在页面上显示通知或提示信息，如成功、警告、错误等消息
import { Message } from '@arco-design/web-vue'
// import { sourceMapsEnabled } from 'process'
// import { h } from 'vue'
// import { log } from 'console'

//用于存储班级信息数组,初始为空
let classesListInfo = ref([])

// enrollInfoArr: 用于存储报名信息的数组，初始值为空数组
let enrollInfoArr = ref([])

// 准备一个数组用来存放classId为空的记录
const recordsWithEmptyClassId = ref([])

// total: 记录数据总数的变量，初始值为0
let total = ref<number>(0)

let total02 = ref<number>(0)

// pageNo: 当前页码，初始值为1
let pageNo = ref<number>(1)

// pageSize: 每页显示的数据条数，初始值为10
let pageSize = ref<number>(10)

// keyword: 搜索关键词，用于筛选数据，初始值为空字符串
// let keyword = ref<String>()

// classesId: 班级ID，用于存储班级ID，初始值为空引用
let classesIds = ref()

// selectEroll: 用于存储选中的报名信息，初始值为空数组
let selectEroll = ref([])

// formRef: 表单组件的引用，用于访问表单实例和进行操作，初始值为空引用
// let formRef = ref()

// dateRange: 日期范围选择器的值，用于存储选定的日期范围，初始值为空引用
// let dateRange = ref()

// visible: 控制弹窗或组件可见性的布尔值，初始值为false，即默认不可见
const visible = ref(false)
// visible02: 控制抽屉组件可见性的布尔值，初始值为false，即默认不可见
const visible02 = ref(false)

// 定义抽屉弹出的位置，默认为'top'
const position = ref('top')

//初始化一个标志位,用于表示事件是否已经触发,默认true
const isFirstTime = ref(true)

//用于存储输入框数据
const inputInfo = ref('')
//用于储存勾选框中的数据
const checkedList = ref(['小班', '中班', '大班'])

const stuinfo: StuInfo = reactive({
  name: '',
  gender: 0, //性别
  stu_avatar: '', //学生头像
  birth_date: [], //出生日期
  id_number: 0, //学身份证
  household_register: '', //户口所在地
  current_address: '', //现住地址
  emergency_contact_name: '', //紧急联系人姓名
  emergency_contact_phone: '', //紧急联系人电话
  bind_code: '', //绑定码
  admission_date: [], //入圆日期
  class_grade_level: '', //所属年级
  is_graduated: 0, //是否离圆
})
// 异步函数，用于获取学生信息，默认从第一页开始查询
const getStuByNameAndLevelInfo = async (pager = 1) => {
  if (inputInfo.value === '' || inputInfo.value === null) {
    inputInfo.value = '靠'
  }
  pageNo.value = pager
  let result: any = await getStuByNameAndClassLevels(
    pageNo.value,
    pageSize.value,
    inputInfo.value,
    checkedList.value,
  )
  if (result.status == 'OK') {
    result.data.records.forEach((record: any) => {
      if (record.graduated == false) {
        record.graduated = '退学'
      } else {
        record.graduated = '在读'
      }
    })
    if (
      (inputInfo.value == '' ||
        inputInfo.value == null ||
        inputInfo.value == '靠') &&
      checkedList.value.length == 0
    ) {
      console.log('空值,全是空值')

      enrollInfoArr.value = []
    } else {
      enrollInfoArr.value = result.data.records
    }
  }
}

//输入框清除事件
const clearInput = () => {
  console.log('我靠')
  inputInfo.value = '靠'
  getStuByNameAndLevelInfo()
}
//输入框触发事件
const InputTrigger = (event: string) => {
  inputInfo.value = event
  console.log('勾选:', checkedList.value)

  getStuByNameAndLevelInfo()
}
//勾选框触发事件
const onChange = (event: never[]) => {
  checkedList.value = event
  console.log('触发了勾选框事件', checkedList.value)
  getStuByNameAndLevelInfo()
}

const classroom: Classrs = reactive({
  classId: 0,
  className: '',
})

// 处理点击按钮打开抽屉的逻辑
const handleClick = () => {
  visible02.value = true
}

// 处理点击确定按钮的逻辑
const handleOk = () => {
  console.log('OK button clicked')
  // 在这里可以添加关闭抽屉前需要执行的业务逻辑
  visible02.value = false
}

// 处理点击取消按钮或遮罩层关闭抽屉的逻辑
const handleCancel = () => {
  console.log('Cancel button or mask clicked')
  visible02.value = false
}

//下拉框选中改变事件
const onStatusChange = (records: any, record02: any) => {
  // 遍历数组
  classesListInfo.value.forEach(async (record: any) => {
    if (record.className == records) {
      console.log('这是' + records + '的班级ID' + record.classId)
      record02.classId = record.classId

      // 将之前改的数据改回 布尔类型
      record02.graduated = '退学' ? false : true
      // 修改
      let result = await reqAssignUpdateClasses(record02)
      console.log(result.message)
      if (result.status === 'OK') {
        // 显示成功消息，`Message.success`为假设的全局消息提示方法
        Message.success(result.message)
      }
      getStuInfo()
      // 清空数据存储的数组
      recordsWithEmptyClassId.value = []
    }
  })
}

//下拉框显示事件
const onVisibleChange = async (record: any) => {
  if (isFirstTime.value) {
    let classesLevel =
      record.classGradeLevel === '小班'
        ? 1
        : record.classGradeLevel === '中班'
          ? 2
          : record.classGradeLevel === '大班'
            ? 3
            : 4
    console.log('你妈妈', classesLevel)

    //得到下拉框需要的数据需要
    let result: any = await reqClassesInfoListDistribute(classesLevel)
    if (result.status === 'OK') {
      // 显示成功消息，`Message.success`为假设的全局消息提示方法
      // Message.success(result.message)
      classesListInfo.value = result.data
      console.log('OK', classesListInfo.value)
    }
    //最后将控制标志设置为false防止反复执行
    // isFirstTime.value = false
  }
}

// 打开模态框
// const openVisible = () => {
//   Object.assign(classroom, {
//     classId: 0,
//     className: '',
//   })
//
//清除上一次的错误的提示信息
// nextTick(() => {
//   // formRef.value.clearValidate()
// })
//
//   visible.value = true
// }

// 模态框点击确定
// const handleBeforeOk = () => {
//   formRef.value.validate(async (r: any, _Record: any) => {
//     if (r === undefined) {
//       // 发送请求
//       let result = await reqAssignUpdateClasses(classesIds)
//       // 如果请求返回的状态为'OK'
//       if (result.status === 'OK') {
//         // 显示成功消息，`Message.success`为假设的全局消息提示方法
//         Message.success(result.message)
//         //修改完成后刷新页面/重新查询
//         getStuInfo()
//         // 关闭模态框
//         visible.value = false
//       } else {
//         // 如果请求失败，显示错误消息
//         Message.error(result.message)
//       }
//     }
//   })
// }

// 获取用户数据
const getStuInfo = async (pager = 1) => {
  // 收集当前的页码
  pageNo.value = pager
  let result: any = await reqstupageinfo(pageNo.value, pageSize.value)

  if (result.status === 'OK') {
    recordsWithEmptyClassId.value = []
    //在保存数据前先做出判断，更改页面显示数据
    result.data.records.forEach((record: any) => {
      if (record.graduated == false) {
        record.graduated = '退学'
      } else {
        record.graduated = '在读'
      }

      // 筛选classId为空的记录
      if (!record.classId || record.classId == 0) {
        recordsWithEmptyClassId.value.push(record)
        console.log('找到classId为空的记录')
        console.log(recordsWithEmptyClassId.value)
        console.log(result.data.records)

        total02.value = total02.value + 1
      }
    })

    //将数据存入响应式数组中
    enrollInfoArr.value = result.data.records
    //保存数据条数
    total.value = result.data.total
  }
}
// 页码改变
const pageSizeChange = (value: number) => {
  pageSize.value = value
  getStuInfo(pageNo.value)
}

// 在组件挂载完成后立即获取学生信息列表
onMounted(() => {
  //调用方法
  getStuInfo()
})
</script>

<style lang="scss" scoped></style>
